package com.situ.mall.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.mall.pojo.User;

// /*代表拦截所有的请求
@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String method = httpServletRequest.getParameter("method");
		
		//对一些要去完成登录的操作，放行，不去判断是否已经登录
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		if (servletPath.endsWith(".jpg")
				|| servletPath.endsWith(".js")
				|| servletPath.endsWith(".css")
				|| servletPath.endsWith("/login.jsp")
				|| servletPath.equals("/user") && method.equals("login")) {
			chain.doFilter(request, response);
			return;
		}
		
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
			return;
		}
		
		//用户已经登录了，放行
		chain.doFilter(request, response);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
